package router

import (
	"bysy-gin/router/relative"
	"bysy-gin/router/student"
	"bysy-gin/router/user"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

func Load(g *gin.Engine) {
	//添加路由
	g.GET("/", login)
	g.POST("/:id", handle_login) //传递动态url

	//g.GET("/register", register)
	//g.POST("/register", handleRegister)
	//加载student的路由
	student.Stu_Load(g)
	//加载user路由
	user.UserLoad(g)
	//加载 数据库关系路由
	relative.Relation_Load(g)
}

func login(c *gin.Context) {
	c.HTML(200, "index.html", gin.H{})
}

func handle_login(c *gin.Context) {
	/*
		url的传递方式：
					Param    动态url
				    Query     url携带查询参数
					PostForm  表单数据
					BindJson  接收传入的json数据
			        ShouldBindJson
	*/
	id := c.Param("id")            //获取动态url
	user := c.PostForm("username") //获取表单数据
	passwd := c.PostForm("password")
	if user != "sc" || passwd != "123456" {
		c.HTML(401, "index.html", gin.H{"message": "用户或密码错误！"})
	}
	fmt.Println(user, passwd, id)
	c.Redirect(http.StatusMovedPermanently, "/student") //跳转到别的url
}

/*
练习
添加/register  --> Register
页面上使用bootstrap样式  添加用户名、密码、性别
将这些信息写入map保存
结构体--》  User  username、passwd、sex
{“root”: user}
*/

func register(c *gin.Context) {
	c.HTML(200, "register.html", gin.H{})
}

func handleRegister(c *gin.Context) {

	//username := c.PostForm("username")
	//passwd1 := c.PostForm("passwd1")
	//passwd2 := c.PostForm("passwd2")
	//fmt.Println(passwd2)
	//if passwd1 != passwd2 {
	//	c.HTML(401, "register.html", gin.H{"message": "两次密码不相等！"})
	//}
	//age := c.PostForm("age")
	//user := User{Passwd: passwd1, Age: age}
	//Users[username] = user
	//fmt.Print(Users)
	//c.HTML(200, "register.html", gin.H{"message": "注册成功！"})

	var user UserJson
	if err := c.ShouldBindJSON(&user); err != nil {
		c.JSON(501, gin.H{"error": err})
		return
	}
	fmt.Printf("%+v", user)
	c.JSON(200, gin.H{"user": user})
}

/*
1、将注册视图处理函数 写入handler/register
2、注册成功，返回json格式数据
*/

/*
创建用户数据表  user
字段： id   name  password  address
创建好数据模型
实现用户注册和登录，前端界面也要有
提示登录、注册成功或失败
*/
